import 'package:flutter/material.dart';  // 🔥 导入Flutter Material库
import 'package:get/get.dart';
import 'package:playtruly/common/api/activity_api.dart';
import 'package:playtruly/common/api/user_api.dart';  // 🔥 导入用户API（用于获取用户信息）
import 'package:playtruly/common/models/index.dart';
import 'package:playtruly/common/services/user_service.dart';
import 'package:playtruly/common/services/rongcloud_service.dart';  // 🔥 新增：融云服务导入
import 'package:playtruly/common/utils/toast_util.dart';
import 'package:playtruly/common/routers/names.dart';  // 🔥 导入路由名称
import 'dart:developer' as developer;

/// 活动申请用户管理控制器
class ActivityApplicationManagementController extends GetxController {
  ActivityApplicationManagementController();

  // 获取UserService实例
  UserService get userService => UserService.to;

  /// 参与者列表
  final RxList<PublisherParticipantsData> _participants = <PublisherParticipantsData>[].obs;
  List<PublisherParticipantsData> get participants => _participants;

  /// 是否正在加载
  final RxBool _isLoading = false.obs;
  bool get isLoading => _isLoading.value;

  /// 是否正在审核
  final RxBool _isReviewing = false.obs;
  bool get isReviewing => _isReviewing.value;

  /// 待审核参与者（置顶显示）
  List<PublisherParticipantsData> get pendingParticipants => 
      _participants.where((p) => p.isPending).toList();

  /// 已通过参与者
  List<PublisherParticipantsData> get approvedParticipants => 
      _participants.where((p) => p.isApproved).toList();

  /// 已拒绝参与者
  List<PublisherParticipantsData> get rejectedParticipants => 
      _participants.where((p) => p.isRejected).toList();

  /// 排序后的参与者列表（待审核置顶）
  List<PublisherParticipantsData> get sortedParticipants {
    final sorted = [..._participants];
    sorted.sort((a, b) {
      if (a.isPending && !b.isPending) return -1;
      if (!a.isPending && b.isPending) return 1;
      // 按申请时间排序（最新的在前）
      return b.applicationTime.compareTo(a.applicationTime);
    });
    return sorted;
  }

  @override
  void onInit() {
    super.onInit();
    _loadParticipants();
  }

  /// 加载参与者数据
  Future<void> _loadParticipants() async {
    try {
      if (!userService.isLoggedIn || userService.currentUser == null) {
        developer.log('❌ 用户未登录，无法加载参与者数据');
        ToastUtil.error('请先登录');
        return;
      }

      _isLoading.value = true;
      developer.log('🔄 开始加载发布者活动参与者数据...');

      final publisherId = userService.currentUser!.userid;
      developer.log('👤 发布者ID: $publisherId');

      // 调用API获取参与者数据
      final response = await ActivityApi.getPublisherActivityParticipants(
        publisherId: publisherId,
      );

      if (response.isSuccess) {
        _participants.value = response.participants;
        developer.log('✅ 参与者数据加载成功');
        developer.log('👥 总参与者数: ${response.total}');
        developer.log('⏳ 待审核: ${response.pendingParticipants.length}');
        developer.log('✅ 已通过: ${response.approvedParticipants.length}');
        developer.log('❌ 已拒绝: ${response.rejectedParticipants.length}');
      } else {
        developer.log('❌ 参与者数据加载失败: ${response.message}');
        ToastUtil.error('加载参与者数据失败: ${response.message}');
      }
    } catch (e) {
      developer.log('💥 加载参与者数据异常: $e');
      ToastUtil.error('加载参与者数据异常: $e');
    } finally {
      _isLoading.value = false;
    }
  }

  /// 刷新参与者数据
  Future<void> refreshParticipants() async {
    await _loadParticipants();
  }

  /// 通过申请
  Future<void> approveApplication(PublisherParticipantsData participant) async {
    if (_isReviewing.value) {
      developer.log('⚠️ 正在审核中，请稍后');
      return;
    }

    try {
      _isReviewing.value = true;
      developer.log('🔄 开始通过申请...');
      developer.log('👤 用户: ${participant.userName} (${participant.userId})');
      developer.log('🎯 活动: ${participant.activityName} (${participant.activityId})');

      // 调用审核API
      final response = await ActivityApi.reviewParticipantApplication(
        activityId: participant.activityId,
        userId: participant.userId,
        reviewStatus: 'approved',
        reviewNote: '同意加入活动',
      );

      if (response.isSuccess) {
        developer.log('✅ 申请通过成功');
        
        // 🔥 新增：发送融云IM通知消息（模仿MyApplication2的实现）
        await _sendRongCloudNotification(
          participant: participant, 
          isApproved: true,
        );
        
        // 更新本地数据
        final index = _participants.indexWhere((p) => 
            p.userId == participant.userId && p.activityId == participant.activityId);
        if (index != -1) {
          // 创建新的参与者数据（状态更新为已通过）
          final updatedParticipant = PublisherParticipantsData(
            userId: participant.userId,
            userName: participant.userName,
            userAge: participant.userAge,
            userGender: participant.userGender,
            userAvatarUrl: participant.userAvatarUrl,
            userSignature: participant.userSignature,
            activityId: participant.activityId,
            activityName: participant.activityName,
            applicationTime: participant.applicationTime,
            participantStatus: 'approved', // 更新状态
            userLevel: participant.userLevel,
            userBirthday: participant.userBirthday, // 🔥 添加生日字段
            extraData: participant.extraData,
          );
          
          _participants[index] = updatedParticipant;
        }

        ToastUtil.success('已允许 ${participant.userName} 加入「${participant.activityName}」活动');
      } else {
        developer.log('❌ 申请通过失败: ${response.message}');
        ToastUtil.error('审核失败: ${response.message}');
      }
    } catch (e) {
      developer.log('💥 通过申请异常: $e');
      ToastUtil.error('审核异常: $e');
    } finally {
      _isReviewing.value = false;
    }
  }

  /// 拒绝申请
  Future<void> rejectApplication(PublisherParticipantsData participant) async {
    if (_isReviewing.value) {
      developer.log('⚠️ 正在审核中，请稍后');
      return;
    }

    try {
      _isReviewing.value = true;
      developer.log('🔄 开始拒绝申请...');
      developer.log('👤 用户: ${participant.userName} (${participant.userId})');
      developer.log('🎯 活动: ${participant.activityName} (${participant.activityId})');

      // 调用审核API
      final response = await ActivityApi.reviewParticipantApplication(
        activityId: participant.activityId,
        userId: participant.userId,
        reviewStatus: 'rejected',
        reviewNote: '不符合活动要求',
      );

      if (response.isSuccess) {
        developer.log('✅ 申请拒绝成功');
        
        // 🔥 新增：发送融云IM通知消息（模仿MyApplication2的实现）
        await _sendRongCloudNotification(
          participant: participant, 
          isApproved: false,
        );
        
        // 🔥 修复：更新本地状态为已拒绝，而不是移除记录（保持数据一致性）
        final index = _participants.indexWhere((p) => 
            p.userId == participant.userId && p.activityId == participant.activityId);
        if (index != -1) {
          // 创建新的参与者数据（状态更新为已拒绝）
          final updatedParticipant = PublisherParticipantsData(
            userId: participant.userId,
            userName: participant.userName,
            userAge: participant.userAge,
            userGender: participant.userGender,
            userAvatarUrl: participant.userAvatarUrl,
            userSignature: participant.userSignature,
            activityId: participant.activityId,
            activityName: participant.activityName,
            applicationTime: participant.applicationTime,
            participantStatus: 'rejected', // 更新状态为已拒绝
            userLevel: participant.userLevel,
            userBirthday: participant.userBirthday,
            extraData: participant.extraData,
          );
          
          _participants[index] = updatedParticipant;
        }

        ToastUtil.success('已拒绝 ${participant.userName} 的申请');
      } else {
        developer.log('❌ 申请拒绝失败: ${response.message}');
        ToastUtil.error('审核失败: ${response.message}');
      }
    } catch (e) {
      developer.log('💥 拒绝申请异常: $e');
      ToastUtil.error('审核异常: $e');
    } finally {
      _isReviewing.value = false;
    }
  }

  /// 根据性别获取图标
  String getGenderIcon(String? gender) {
    switch (gender) {
      case '男':
        return '♂';
      case '女':
        return '♀';
      default:
        return '?'; // 未知性别使用问号
    }
  }

  /// 格式化申请时间
  String formatApplicationTime(String timeString) {
    try {
      // 如果已经是格式化的时间字符串，直接返回
      if (timeString.contains('-') && timeString.contains(':')) {
        return timeString;
      }
      
      // 如果是时间戳，进行转换
      final timestamp = int.tryParse(timeString);
      if (timestamp != null) {
        final dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
        return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}:${dateTime.second.toString().padLeft(2, '0')}';
      }
      
      return timeString;
    } catch (e) {
      developer.log('⚠️ 时间格式化失败: $e');
      return timeString;
    }
  }

  /// 🔥 根据积分获取用户等级名称（与个人中心保持一致）
  String getUserLevelText(int? points) {
    if (points == null) points = 0;
    
    if (points >= 1200) {
      return '一言九鼎';
    } else if (points >= 600) {
      return '真神';
    } else if (points >= 300) {
      return '创造者';
    } else if (points >= 100) {
      return '守护者';
    } else {
      return '追随者';
    }
  }

  /// 🔥 根据生日计算年龄
  int calculateAgeFromBirthday(String? birthday) {
    if (birthday == null || birthday.isEmpty) {
      return 0; // 如果没有生日信息，返回0
    }
    
    try {
      // 解析生日字符串 (格式: "1987-03-01")
      final birthDate = DateTime.parse(birthday);
      final now = DateTime.now();
      
      int age = now.year - birthDate.year;
      
      // 检查是否还没到今年的生日
      if (now.month < birthDate.month || 
          (now.month == birthDate.month && now.day < birthDate.day)) {
        age--;
      }
      
      return age;
    } catch (e) {
      developer.log('⚠️ 生日解析失败: $birthday, 错误: $e');
      return 0;
    }
  }

  /// 获取默认头像URL
  String getDefaultAvatarUrl() {
    return 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_16.webp';
  }

  /// 🎯 跳转到用户信息页面（模仿activity_detail_bottom_sheet的逻辑）
  Future<void> goToUserProfile(PublisherParticipantsData participant) async {
    developer.log('🔗 点击头像，跳转到用户信息页面: ${participant.userName}');
    
    try {
      // 🔥 获取用户ID（从participant中获取）
      final targetUserId = participant.userId;
      
      developer.log('👤 开始获取用户信息，用户ID: $targetUserId');
      
      // 显示加载提示
      Get.dialog(
        Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
          ),
        ),
        barrierDismissible: false,
      );
      
      // 🚀 调用用户过滤内容API获取用户信息（与activity_detail_bottom_sheet保持一致）
      final userResponse = await UserApi.getUserFilteredContent(
        userId: targetUserId,
        contentType: 'activities', // 获取活动信息
      );
      
      // 关闭加载对话框
      Get.back();
      
      if (userResponse.isSuccess && userResponse.user != null) {
        final user = userResponse.user!;
        developer.log('✅ 成功获取用户信息: ${user.username}');
        
        // 🎯 将FilteredUserInfo转换为用户信息页面需要的参数（与activity_detail_bottom_sheet保持一致）
        final userInfo = {
          'userId': user.userid,
          'username': user.username,
          'avatar': user.userAvatarUrl ?? '',
          'signature': user.userSignature ?? '',
          'userLevel': user.userLevel ?? 0,
          'userFollowers': user.userFollowers ?? 0,
          'userLikes': user.userLikes ?? 0,
          'userPoints': user.userPoints ?? 0, // 🔥 积分字段支持等级显示
          'userTags': user.userTags ?? [],
          'userHobbies': user.userHobbies ?? [],
          'userFrequentPlaces': user.userFrequentPlaces ?? '未知',
          'userCity': user.userCity ?? '未知',
          'userImgUrls': user.userImgUrls ?? [],
          'activities': userResponse.activities ?? [], // List<ActivityData>
          'friendCount': userResponse.friendCount ?? 0,
        };
        
        // 🚀 跳转到用户信息页面
        Get.toNamed(
          RouteNames.myUserInfo,
          arguments: userInfo,
        );
        
        developer.log('✅ 用户信息页面跳转完成');
      } else {
        developer.log('❌ 获取用户信息失败: ${userResponse.message}');
        ToastUtil.error('获取用户信息失败: ${userResponse.message ?? "未知错误"}');
      }
      
    } catch (e) {
      // 关闭可能的加载对话框
      if (Get.isDialogOpen == true) {
        Get.back();
      }
      developer.log('💥 获取用户信息异常: $e');
      ToastUtil.error('获取用户信息失败');
    }
  }

  /// 🔥 新增：发送融云IM通知消息（模仿MyApplication2的实现）
  Future<void> _sendRongCloudNotification({
    required PublisherParticipantsData participant,
    required bool isApproved,
  }) async {
    try {
      developer.log('📨 =============== 发送活动申请审核结果通知 ===============');
      developer.log('👤 申请者: ${participant.userName} (ID: ${participant.userId})');
      developer.log('🎯 活动: ${participant.activityName}');
      developer.log('✅ 审核结果: ${isApproved ? "通过" : "拒绝"}');
      
      // 🔥 获取申请者的融云用户ID
      String? targetRongCloudUserId = _getRongCloudUserId(participant);
      
      if (targetRongCloudUserId == null || targetRongCloudUserId.isEmpty) {
        developer.log('⚠️ 无法获取申请者的融云用户ID，跳过消息发送');
        return;
      }
      
      developer.log('🎯 目标融云用户ID: $targetRongCloudUserId');
      
      // 🔥 构造通知消息内容（参考MyApplication2格式）
      final messageContent = isApproved 
          ? '您申请加入「${participant.activityName}」活动的申请已通过，请准时参加活动！' 
          : '很抱歉，您申请加入「${participant.activityName}」活动的申请未通过，请关注其他精彩活动！';
      
      developer.log('💬 消息内容: $messageContent');
      
      // 🔥 通过融云服务发送消息
      final rongCloudService = RongCloudService.to;
      final success = await rongCloudService.sendTextMessage(
        targetId: targetRongCloudUserId,
        content: messageContent,
      );
      
      if (success) {
        developer.log('✅ 活动申请审核结果通知发送成功');
      } else {
        developer.log('❌ 活动申请审核结果通知发送失败');
      }
      
    } catch (e) {
      developer.log('💥 发送融云IM通知异常: $e');
    }
  }

  /// 🔥 获取申请者的融云用户ID
  String? _getRongCloudUserId(PublisherParticipantsData participant) {
    try {
      // 🎯 方法1：从extraData中获取融云用户ID
      if (participant.extraData != null && 
          participant.extraData!['rongcloud_user_id'] != null) {
        final rongCloudId = participant.extraData!['rongcloud_user_id'].toString();
        if (rongCloudId.isNotEmpty) {
          developer.log('🎯 从extraData获取融云ID: $rongCloudId');
          return rongCloudId;
        }
      }
      
      // 🎯 方法2：从extraData中获取手机号（作为备选）
      if (participant.extraData != null && 
          participant.extraData!['userPhone'] != null) {
        final userPhone = participant.extraData!['userPhone'].toString();
        if (userPhone.isNotEmpty) {
          developer.log('📱 从extraData获取手机号作为融云ID: $userPhone');
          return userPhone;
        }
      }
      
      // 🎯 方法3：使用用户ID作为最后备选（如果MyApplication2使用相同规则）
      if (participant.userId > 0) {
        final userIdString = participant.userId.toString();
        developer.log('🆔 使用用户ID作为融云ID: $userIdString');
        return userIdString;
      }
      
      developer.log('❌ 无法获取融云用户ID');
      return null;
      
    } catch (e) {
      developer.log('💥 获取融云用户ID异常: $e');
      return null;
    }
  }

  @override
  void onClose() {
    super.onClose();
    developer.log('🔄 ActivityApplicationManagementController 已销毁');
  }
}
